const DATA_CACHE = []; // 数据缓存

let timer_flip = null; // 翻页计时器ID

$(document).ready(function() {
  let data = localStorage.getItem("data");
  if (data) { // 获取图库数据用于翻页
    localStorage.removeItem("data");
    DATA_CACHE.splice(0); // 清空
    DATA_CACHE.push(...JSON.parse(data));
  }
  fixResolution(); // 读取显示分辨率（刷新页面可能无法触发load）
  let img = $(".image-display img");
  img.on("load", function () { // 原图加载完成
    fixResolution(); // 读取显示分辨率
  });
  img.click(function(event) { // 切换图片模式
    toggleImgFit(event.offsetX, event.offsetY);
  });
  img.mousewheel(function(event) { // 依赖 jquery-mousewheel
    console.log(event.deltaY);
    if (event.deltaY > 0) { // 向前滚动
      clearTimeout(timer_flip);
      timer_flip = setTimeout("next()", 240);
    } else if (event.deltaY < 0) { // 向后滚动
      clearTimeout(timer_flip);
      timer_flip = setTimeout("next(true)", 240);
    }
  });
  $(document).keydown(function(e) {
    if (e.keyCode === 13) { // Enter
      e.preventDefault();
      toggleFullScreen();
    } else if (e.keyCode === 32) { // Space
      e.preventDefault();
      toggleImgFit();
    } else if (e.keyCode === 37 || e.keyCode === 38) { // Left / Up
      e.preventDefault();
      clearTimeout(timer_flip);
      timer_flip = setTimeout("next()", 240);
    } else if (e.keyCode === 39 || e.keyCode === 40) { // Right / Down
      e.preventDefault();
      clearTimeout(timer_flip);
      timer_flip = setTimeout("next(true)", 240);
    } else if (e.keyCode === 8 || e.keyCode === 46) { // Backspace / Delete
      e.preventDefault();
      markDislike();
    } else if (e.keyCode === 53) { // 5 / Ctrl+5
      e.preventDefault();
      markR18();
    } else if (e.ctrlKey && e.keyCode === 55) { // Ctrl+7
      e.preventDefault();
      markJournal();
    } else if (e.ctrlKey && (e.keyCode === 83 || e.keyCode === 68)) { // Ctrl+S / Ctrl+D
      e.preventDefault();
      save();
    } else if (e.ctrlKey && e.keyCode === 70) { // Ctrl+F
      e.preventDefault();
      search();
    } else if (e.ctrlKey && e.keyCode === 71) { // Ctrl+G
      if (URL_API_FIX) {
        e.preventDefault();
        fix();
      }
    }
  });
});

/**
 * 全屏指南：https://developer.mozilla.org/zh-CN/docs/Web/API/Fullscreen_API/Guide
 */
function toggleFullScreen() {
  if (!document.fullscreenElement) { // 切换全屏
    document.documentElement.requestFullscreen().then();
  } else { // 退出全屏
    if (document.exitFullscreen) {
      document.exitFullscreen().then();
    }
  }
}

function toggleImgFit(targetX=-1, targetY=-1) {
  let img = $(".image-display img");
  if (img.css("object-fit") === "cover") { // 切换全图
    img.css("object-position", "center center")
      .css("object-fit", "contain")
      .css("cursor", "zoom-in");
  } else { // 切换填充
    if (targetX >= 0 && targetY >= 0) { // 根据点击位置针对性缩放
      img.css("object-position", `${(targetX / img.innerWidth() * 100)}% ${(targetY / img.innerHeight() * 100)}%`)
        .css("object-fit", "cover")
        .css("cursor", "zoom-out");
    } else { // 居中填充
      img.css("object-position", "center center")
        .css("object-fit", "cover")
        .css("cursor", "zoom-out");
    }
  }
}

function fixResolution() {
  let img = $(".image-display img");
  // jQuery对象转JavaScript对象，使用原生方法获取原图尺寸
  let width = img.get(0).naturalWidth;
  let height = img.get(0).naturalHeight;
  if (width > 0 && height > 0) {
    $(".nav-image-info strong:eq(1)").text(`${width}x${height}`);
  }
}

function next(reverse=false) {
  if (DATA_CACHE.length === 0) {
    return;
  }
  let id = $(".image-display img").attr("data-id");
  let ids = DATA_CACHE.map(item => item["id"].toString());
  let index = ids.indexOf(id);
  if (index < 0) {
    localStorage.setItem("data", JSON.stringify(DATA_CACHE));
    location.reload();
    return;
  }
  index = reverse ? index - 1 : index + 1;
  if (index >= DATA_CACHE.length) {
    index = DATA_CACHE.length - 1;
  } else if (index < 0) {
    index = 0;
  }
  localStorage.setItem("data", JSON.stringify(DATA_CACHE));
  // location.assign 会记入历史且可回退
  location.replace("/unbox/" + DATA_CACHE[index]["id"]);
}

function markDislike(undo=false) {
  if (!$.cookie("fingerprint")) {
    return;
  }
  let img = $(".image-display img");
  let data_req = {
    provider: img.attr("data-rp"),
    imgid: img.attr("data-ri"),
    imgurl: img.attr("src"),
    action: "dislike",
    undo: undo ? 1 : 0,
    deviceid: $.cookie("fingerprint"),
    client: CLIENT
  };
  fetch("https://api.nguaduot.cn/appstats/rank", {
    method: "POST",
    body: JSON.stringify(data_req)
  }).then(response => response.json())
    .then(data => {
      if (data && data["status"] === 1) {
        if (!undo && !confirm("已标记：我不喜欢")) {
          markDislike(true);
        }
      } else {
        alert(undo ? "撤销标记出错" : "标记出错");
      }
    })
    .catch(console.error);
}

function markR18(undo=false) {
  if (!$.cookie("fingerprint")) {
    return;
  }
  let img = $(".image-display img");
  let data_req = {
    provider: img.attr("data-rp"),
    imgid: img.attr("data-ri"),
    imgurl: img.attr("src"),
    action: "r18",
    undo: undo ? 1 : 0,
    deviceid: $.cookie("fingerprint"),
    client: CLIENT
  };
  fetch("https://api.nguaduot.cn/appstats/rank", {
    method: "POST",
    body: JSON.stringify(data_req)
  }).then(response => response.json())
    .then(data => {
      if (data && data["status"] === 1) {
        if (!undo && !confirm("已标记：有色气")) {
          markR18(true);
        }
      } else {
        alert(undo ? "撤销标记出错" : "标记出错");
      }
    })
    .catch(console.error);
}

function markJournal(undo=false) {
  if (!$.cookie("fingerprint")) {
    return;
  }
  let img = $(".image-display img");
  let data_req = {
    provider: img.attr("data-rp"),
    imgid: img.attr("data-ri"),
    imgurl: img.attr("src"),
    action: "journal",
    undo: undo ? 1 : 0,
    deviceid: $.cookie("fingerprint"),
    client: CLIENT
  };
  fetch("https://api.nguaduot.cn/appstats/rank", {
    method: "POST",
    body: JSON.stringify(data_req)
  }).then(response => response.json())
    .then(data => {
      if (data && data["status"] === 1) {
        if (!undo && !confirm("已标记：周度精选")) {
          markJournal(true);
        }
      } else {
        alert(undo ? "撤销标记出错" : "标记出错");
      }
    })
    .catch(console.error);
}

function save() {
  let a = document.createElement("a");
  a.href = "/raw/" + $(".image-display img").attr("data-id");
  a.referrerPolicy = "no-referrer";
  a.target = "_blank";
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

function search() {
  if (confirm("调用 Google 以图搜图？")) {
    let img_url = $(".image-display img").attr("src");
    let search_url = "https://lens.google.com/uploadbyurl?url=" + encodeURIComponent(img_url);
    window.open(search_url, "_blank");
  }
}

function fix() {
  let cmd = prompt(HINT_FIX ? HINT_FIX : "反馈");
  if (!cmd) {
    return;
  }
  let url_api = URL_API_FIX.replace("{id}", $(".image-display img").attr("data-ri"))
    .replace("{cmd}", encodeURIComponent(cmd));
  fetch(url_api).then(function(response) {
    response.json().then(function(res) {
      if (res && res["status"] === 1) {
        alert(res["msg"] ? res["msg"] : "提交成功");
      } else {
        alert("提交出错");
      }
    });
  }).catch(console.error);
}